package com.tx.product.controller;

import com.google.gson.Gson;
import com.tx.DBUtil;
import com.tx.model.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/productList.do")
public class ProductListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取连接
        Connection conn = DBUtil.getConnection();
        //2、准备SQL
        String sql = "select * from tb_product order by create_time desc limit 10";
        //3、声明操作对象及结果集对象
        PreparedStatement ps = null;
        ResultSet rs = null;
        //4、获取操作对象
        try {
            ps = conn.prepareStatement(sql);
            //5、执行SQL获取结果集
            rs = ps.executeQuery();
            //6、解析结果集
            ArrayList list = new ArrayList();
            while(rs.next()){
                //7、创建对象并设置数据
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setDescription(rs.getString("description"));
                product.setMarket_price(rs.getDouble("market_price"));
                product.setSell_price(rs.getDouble("sell_price"));
                product.setPicture(rs.getString("picture"));
                //8、将数据添加到列表中
                list.add(product);
                product = null;
            }
            //9、返回数据
            resp.setContentType("application/json;charset=utf-8");
            //需要添加依赖
            Gson gson = new Gson();
            //将List对象转为JSON格式字符串
            String result = gson.toJson(list);
            //输出转换后的字符串数据
            resp.getWriter().println(result);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        DBUtil.closeResource(conn, ps, rs);
    }
}